package com.sample.transaction.atomikos.db1.controller;

import com.sample.transaction.atomikos.db1.entity.User1;
import com.sample.transaction.atomikos.db1.service.User1Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/mulDb1")
public class User1Controller {

    @Autowired
    private User1Service user1Service;

    // http://localhost:8081/mulDb1/get/id/1
    @GetMapping("/get/id/{id}")
    public User1 getUserById(@PathVariable String id){
        log.info("getUserById, id = {}", id);
        return user1Service.findById(Integer.parseInt(id)).orElse(new User1());
    }

    /**
     * 返回json格式数据
     * @param code 编号
     * @return 用户
     */
    @GetMapping("/get/code/{code}")
    public User1 getUserByNumber(@PathVariable String code){
        User1 user = user1Service.findByCode(code);
        return user;
    }

    @GetMapping("/get/all/{page}/{size}")
    public List<User1> getAllUserByPage(@PathVariable("page") int page, @PathVariable("size") int size){
        return user1Service.findAllUserByPage(page,size);
    }


    // http://localhost:8081/mulDb1/update/1/zs/zhangsan
    @GetMapping("/update/{id}/{code}/{name}")
    public User1 addUser(@PathVariable("id") int id,
                         @PathVariable("code") String code, @PathVariable("name") String name, boolean throwEx){
        User1 user = new User1();
        user.setId(id);
        user.setCode(code);
        user.setName(name);
        User1 userNew = null;
        try{
            userNew = user1Service.updateUser(user,throwEx);
        }catch (RuntimeException ex){
            log.error("", ex);
        }
        return userNew;
    }

    @GetMapping("/delete/{id}")
    public void getUserById(@PathVariable("id")int id){
        user1Service.deleteUser(id);
    }

}
